from flask import Blueprint, request, render_template
from app.models import Ward, Bed, Takes, Patient, Case, Doctor, Department
from app.utils import custom_jsonify
import math
from decimal import Decimal

ward_bp = Blueprint('ward', __name__)

@ward_bp.route('/login', methods=['GET'])
def login():
    return render_template('index.html')

@ward_bp.route('/', methods=['GET'])
@ward_bp.route('/bed_information', methods=['GET'])
def homepage():
    return render_template('bed_information.html')


@ward_bp.route('/department/ward/<ward_id>', methods=['GET'])
def get_ward_info_by_id(ward_id):
    ward = Ward.query.filter_by(ward_id=ward_id).first()
    if ward:
        beds = Bed.query.filter_by(ward_id=ward_id).all()
        bed_list = []
        for bed in beds:
            # Find the patient assigned to the bed, if any
            take = Takes.query.filter_by(bed_id=bed.bed_id).first()
            if take:
                patient = Patient.query.filter_by(patient_id=take.patient_id).first()
                patient_name = patient.patient_name if patient else "n"
            else:
                patient_name = "n"

            bed_list.append({
                "bed_id": bed.bed_id,
                "used_status": bed.used_status,
                "patient_name": patient_name
            })

        return custom_jsonify({
            "ward_id": ward.ward_id,
            "dept_name": ward.dept_name,
            "bed_total": ward.bed_total,
            "bed_used": ward.bed_used,
            "location": ward.location,
            "bed_list": bed_list
        }, 200)
    return custom_jsonify({'message': '没有这样的病区'}, 404)



# 获取床位信息（按ID）
@ward_bp.route('/department/ward/bed/<bed_id>', methods=['GET'])
def get_bed_info_by_id(bed_id):
    # 查找床位信息
    bed = Bed.query.filter_by(bed_id=bed_id).first()

    if not bed:
        return custom_jsonify({'message': '没有这张床'}, 404)

    # 查找主治医生信息
    doctor = Doctor.query.filter_by(doctor_id=bed.doctor_id).first()

    # 初始化响应数据
    response = {
        "charge_doctor_id": doctor.doctor_id if doctor else "未知",
        "charge_doctor_name": doctor.doctor_name if doctor else "未知",
        "used_status": bed.used_status
    }

    # 如果床位正在使用，查找病人信息
    if bed.used_status == 1:
        # 查找病人与该床位的关联
        take = Takes.query.filter_by(bed_id=bed_id).first()

        if take:
            # 查找病人信息
            patient = Patient.query.filter_by(patient_id=take.patient_id).first()
            # 查找病例信息
            case = Case.query.filter_by(patient_id=take.patient_id).first()

            if patient and case:
                # 添加病人信息到响应
                response["patient_info"] = {
                    "patient_name": patient.patient_name,
                    "patient_id": patient.patient_id,
                    "gender": patient.gender,
                    "age": patient.age,
                    "doctor_id": case.doctor_id,
                    "doctor_name": doctor.doctor_name,
                    "description": case.description,
                    "in_date": take.in_date.strftime("%Y-%m-%d")
                }
            else:
                response["patient_info"] = {}
        else:
            response["patient_info"] = {}
    else:
        response["patient_info"] = {}

    return custom_jsonify(response, 200)


#单独一个函数，就是获取全部病区名字
@ward_bp.route('/department/wards', methods=['GET'])
def get_all_wards():
    # 查询所有病区
    wards = Ward.query.all()
    # 构建返回的列表
    ward_list = [{
        "dept_name": ward.dept_name,
        "ward_name": ward.ward_id
    } for ward in wards]

    return custom_jsonify(ward_list, 200)

@ward_bp.route('/api/departments', methods=['GET'])
def get_departments():
    departments = Department.query.all()
    return custom_jsonify({
        'msg': 'success',
        'departments': [{
            'dept_name': dept.dept_name,
            'bed_total': dept.bed_total,
            'bed_used': dept.bed_used
        } for dept in departments]
    })

@ward_bp.route('/api/departments/<dept_name>/wards', methods=['GET'])
def get_department_wards(dept_name):
    wards = Ward.query.filter_by(dept_name=dept_name).all()
    return custom_jsonify({
        'msg': 'success',
        'wards': [{
            'ward_id': ward.ward_id,
            'bed_total': ward.bed_total,
            'bed_used': ward.bed_used,
            'location': ward.location
        } for ward in wards]
    })

@ward_bp.route('/api/beds', methods=['GET'])
def get_beds():
    dept_name = request.args.get('dept')
    ward_id = request.args.get('ward')
    
    query = Bed.query.join(Ward)
    if ward_id:
        query = query.filter(Bed.ward_id == ward_id)
    elif dept_name:
        query = query.filter(Ward.dept_name == dept_name)
    
    beds = query.all()
    
    total_beds = len(beds)
    used_beds = sum(1 for bed in beds if bed.used_status == 1)
    
    return custom_jsonify({
        'msg': 'success',
        'stats': {
            'total': total_beds,
            'used': used_beds,
            'rate': round(used_beds / total_beds * 100 if total_beds > 0 else 0, 1)
        },
        'beds': [{
            'bed_id': bed.bed_id,
            'ward_id': bed.ward_id,
            'dept_name': bed.ward_info.dept_name,
            'used_status': bed.used_status,
            'patient_name': get_patient_name(bed.bed_id) if bed.used_status == 1 else None
        } for bed in beds]
    })

def get_patient_name(bed_id):
    take = Takes.query.filter_by(bed_id=bed_id).first()
    if take:
        patient = Patient.query.get(take.patient_id)
        return patient.patient_name if patient else 'Unknown'
    return None

@ward_bp.route('/api/beds/<bed_id>', methods=['GET'])
def get_bed_detail(bed_id):
    try:
        bed = Bed.query.get(bed_id)
        if not bed:
            return custom_jsonify({
                'msg': 'failed',
                'error': '床位不存在'
            }, 404)

        # 获取床位相关信息
        ward = Ward.query.get(bed.ward_id)
        doctor = Doctor.query.get(bed.doctor_id)
        
        # 获取病人信息（如果床位被占用）
        patient_info = None
        if bed.used_status == 1:
            take = Takes.query.filter_by(bed_id=bed_id).first()
            if take:
                patient = Patient.query.get(take.patient_id)
                case = Case.query.get(take.case_id)
                if patient and case:
                    patient_info = {
                        'patient_name': patient.patient_name,
                        'patient_id': patient.patient_id,
                        'gender': patient.gender,
                        'age': patient.age,
                        'in_date': take.in_date.strftime('%Y-%m-%d %H:%M') if take.in_date else None,
                        'description': case.description,
                        'predict_days': float(case.predict_days) if case.predict_days else None
                    }

        return custom_jsonify({
            'msg': 'success',
            'bed_info': {
                'bed_id': bed.bed_id,
                'ward_id': bed.ward_id,
                'ward_name': ward.dept_name if ward else None,
                'location': ward.location if ward else None,
                'used_status': bed.used_status,
                'doctor_name': doctor.doctor_name if doctor else None,
                'doctor_id': doctor.doctor_id if doctor else None,
                'patient_info': patient_info
            }
        })
    except Exception as e:
        return custom_jsonify({
            'msg': 'failed',
            'error': str(e)
        }, 500)

def bed_recommend(case_id):
    # 1.根据病人病历获取病人信息
    patient = Case.query.filter_by(case_id=case_id).first()
    # 2.根据病人具体信息: 平均时间 各个病区的平均住院时间/总床位数/使用床位数给出病区分数和推荐
    wards = Ward.query.all()
    empty_beds = {ward.ward_id:(ward.bed_total-ward.bed_used) for ward in wards}
    max_emptybeds = max(empty_beds.values())

    f_count = {ward.ward_id : min(1,empty_beds[ward.ward_id] / max_emptybeds) for ward in wards} ##空床数分数
    f_rate = {ward.ward_id : empty_beds[ward.ward_id] / ward.bed_total for ward in wards}  ##空窗率分数
    
    D_max = 10
    f_match = {ward.ward_id : (1-min(D_max,abs(patient.predict_days-ward.avg_time))/D_max) for ward in wards }  ##平均住院时间匹配率

    w1 = 0.5
    w2 = 0.3
    w3 = 0.2
    score = {ward.ward_id : (w1*float(f_count[ward.ward_id]) + w2*float(f_rate[ward.ward_id]) + w3*float(f_match[ward.ward_id])).__format__('.3f') for ward in wards}  ##综合得分

    return score



@ward_bp.route('/api/ward/recommend',methods=['POST'])
def recommend_ward():
    data = request.get_json()
    case_id = data.get('case_id')
    if not case_id:
        return custom_jsonify({
            'msg': 'failed',
            'error': '病历号不能为空'
        }, 407)
    
    score = bed_recommend(case_id)
    score = sorted(score.items(),key=lambda x:x[1],reverse=True)
    score = dict(score)
    return custom_jsonify({
        'msg': 'success',
        'recommend_ward':(score)
    })


